classdef Grid<handle
    %GRID 小球所在网格
    %   此处显示详细说明
    
    properties
        I, J
        C
        nx, ny
        cells
        colormap
        start_points
        picture
        color
    end
    
    methods
        function obj = Grid(i_num, j_num)
            %GRID 构造此类的实例
            %   此处显示详细说明
            obj.I = i_num;
            obj.J = j_num;
            obj.C = zeros([i_num*j_num 1]);
            idx1 = sub2ind([obj.I, obj.J],1, 1);
            idx2 = sub2ind([obj.I, obj.J],1, obj.J);
            idx3 = sub2ind([obj.I, obj.J],obj.I, 1);
            idx4 = sub2ind([obj.I, obj.J],obj.I, obj.J);
            obj.C([idx1,idx2,idx3,idx4]) = [1 2 3 4];
            [x, y] = ndgrid(0:i_num, 0:j_num);
            obj.nx = x(:); obj.ny = y(:);
            [i, j] = ndgrid(1:i_num, 1:j_num);
            obj.start_points = zeros([4,2]);
            obj.start_points(1,:) = [i(idx1)-0.5 j(idx1)-0.5];
            obj.start_points(2,:) = [i(idx2)-0.5 j(idx2)-0.5];
            obj.start_points(3,:) = [i(idx3)-0.5 j(idx3)-0.5];
            obj.start_points(4,:) = [i(idx4)-0.5 j(idx4)-0.5];
            obj.cells = [(j(:)-1)*(i_num+1)+(i(:)-1)+1, ...
                        (j(:)-0)*(i_num+1)+(i(:)-1)+1, ...
                        (j(:)-0)*(i_num+1)+(i(:)-0)+1, ...
                        (j(:)-1)*(i_num+1)+(i(:)-0)+1 ];
            obj.colormap = [1 0 1;0 1 0;0 0 1;1 1 0];
            obj.color = ones([obj.I*obj.J, 1, 3]);
        end

        function idx = get_cell(obj, x, y)
            idx = sub2ind([obj.I, obj.J], ceil(x), ceil(y));
        end

        function dyeing(obj, particles)
            idx = obj.get_cell(particles.T.x, particles.T.y);
            for pid = length(idx):-1:1
                if obj.C(idx(pid)) ~= particles.T.C(pid)
                    obj.C(idx(pid)) = particles.T.C(pid);
                    particles.delete_particles(pid);
                end
            end
        end
        
        function plot_grid(obj)
            %PLOT_GRID 此处显示有关此方法的摘要
            %   此处显示详细说明
            figure(1)
            clf
            obj.color(obj.C>0,:,:) = obj.colormap(obj.C(obj.C>0),:);
            obj.picture = patch(obj.nx(obj.cells'),obj.ny(obj.cells'),obj.color,EdgeColor='none');
            axis equal
            axis off
        end

        function update_grid(obj)
            figure(1)
            obj.color(obj.C>0,:,:) = obj.colormap(obj.C(obj.C>0),:);
            set(obj.picture, 'CData', obj.color);
            drawnow limitrate nocallbacks
        end
    end
end

